/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.itip.event.send;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-2-27 上午10:45:01          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class SendTaskManager {
    private static Logger logger = Logger.getLogger(SendTaskManager.class);

    static final String JOB_KEY_INTERVAL = "interval";

    private static SendTaskManager instance = new SendTaskManager();

    private Scheduler scheduler;

    private SendTaskManager() {
        try {
            scheduler = new StdSchedulerFactory("itip-conf/quartz.properties").getScheduler();
            scheduler.start();
        } catch (SchedulerException e) {
            logger.error("初始化任务管理器失败", e);
        }
    }

    public static SendTaskManager getInstance() {
        return instance;
    }

    /**
     * 初始化从tivoli中获取指标的任务
     */
    public void init() {
        fetchEventTask();
    }

    /**
     * 调度一个Tivoli指标采集任务
     */
    private void fetchEventTask() {
        JobDetail job = null;
        Trigger trigger = null;
        try {
            job = newJob(TransfEventJob.class).withIdentity("event", "TIVOLI").build();
            scheduler.addJob(job, true);
            trigger = makeTrggier(job.getKey(), "Tivoli", 1L, EnvUtil.getInstance().getInterval());
            trigger.getJobDataMap().put(JOB_KEY_INTERVAL, EnvUtil.getInstance().getInterval());
            if (trigger != null) {
                scheduler.scheduleJob(trigger);
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }

    /**
     * 生成一个触发器
     * @param jobKey
     * @param triggerName
     * @param type
     * @param parameter
     * @return
     */
    private Trigger makeTrggier(JobKey jobKey, String triggerName, Long type, String parameter) {
        Trigger trigger = null;
        if (type == 1) {
            int interval = Integer.parseInt(parameter);
            trigger = newTrigger().withSchedule(simpleSchedule().withIntervalInSeconds(interval).repeatForever()).forJob(jobKey).withIdentity(triggerName).startAt(getJobStartTime()).build();
            trigger.getJobDataMap().put(JOB_KEY_INTERVAL, interval);
        } else if (type == 2) {
            try {
                trigger = newTrigger().withSchedule(cronSchedule(parameter)).forJob(jobKey).withIdentity(triggerName).build();
                trigger.getJobDataMap().put(JOB_KEY_INTERVAL, "0");
            } catch (Exception e) {
                logger.error("property refresh timing trggier expression error:" + triggerName, e);
                return null;
            }
        } else {
            return null;
        }
        return trigger;
    }

    /**
     * 多任务情启下 对启动时间作离散
     * @return
     */
    private Date getJobStartTime() {
        Calendar cl = Calendar.getInstance();
        cl.setTimeInMillis(cl.getTimeInMillis() + (long) (Math.random() * 60 * 1000L));
        return cl.getTime();
    }

}
